package com.tj.shopping.web.controller;

import com.tj.shopping.entity.Admin;
import com.tj.shopping.service.IAdminService;
import com.tj.shopping.service.impl.AdminServiceImpl;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/admin")
public class AdminController extends BaseController {
    private IAdminService service = new AdminServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String op = req.getParameter("op");
        if ("add".equals(op)) {
            doAdd(req, resp);
        } else if ("findall".equals(op)) {
            doFindall(req, resp);
        } else if ("findbyid".equals(op)) {
            doFindbyid(req, resp);
        } else if ("delbyid".equals(op)) {
            doDelbyid(req, resp);
        } else if ("update".equals(op)) {
            doUpdate(req, resp);
        } else if ("login".equals(op)) {
            doLogin(req, resp);
        } else {
            resp.getWriter().print("no such Method....");
        }
    }

    private void doFindall(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> m = service.findall();
        printToJson(resp, m);//响应给页面的是m

    }

    private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Admin admin = parseRequest(req, Admin.class);
        Admin admin1 = service.login(admin.getAname(), admin.getApwd());
        printToJson(resp, admin1);//响应给页面的是m

    }

    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Admin admin = parseRequest(req, Admin.class);
        String astate = req.getParameter("astate");
        admin.setAstate(Integer.parseInt(astate));
        int result = service.update(admin);
        // 响应结果给页面
        printToJson(resp, result);

    }

    private void doDelbyid(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void doFindbyid(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, Object> map = parseRequest(req);
        System.out.println(map.get("ano"));
        Map<String, Object> m = service.findbyid(map);
        System.out.println(m);
        printToJson(resp, m);//响应给页面的是m
    }

    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Admin admin = parseRequest(req, Admin.class);
        int result = service.add(admin);
        printToJson(resp, result);
    }
}

    

